﻿using System.Globalization;
using System.Windows.Media;

namespace Gmantis.Controls.Extended
{
    public class WebColor
    {
        // Methods
        public static Color ToColor(string hexColor)
        {
            return ToColor(hexColor, 0xff);
        }

        public static Color ToColor(string hexColor, byte alpha)
        {
            string str;
            if (string.IsNullOrEmpty(hexColor))
            {
                return new Color();
            }
            if (hexColor.StartsWith("#"))
            {
                hexColor = hexColor.Substring(1);
            }
            if ((hexColor.Length != 6) && (hexColor.Length != 8))
            {
                return new Color();
            }
            if (hexColor.Length == 8)
            {
                str = hexColor.Substring(0, 2);
                hexColor = hexColor.Substring(2);
            }
            else
            {
                str = string.Format("{0:X2}", alpha);
            }
            string s = hexColor.Substring(0, 2);
            string str3 = hexColor.Substring(2, 2);
            string str4 = hexColor.Substring(4, 2);
            Color color = new Color();
            try
            {
                int num = int.Parse(str, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                int num2 = int.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                int num3 = int.Parse(str3, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                int num4 = int.Parse(str4, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                color = Color.FromArgb(byte.Parse(num.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture), 
                    byte.Parse(num2.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture), 
                    byte.Parse(num3.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture), 
                    byte.Parse(num4.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture));
            }
            catch
            {
                return new Color();
            }
            return color;
        }
    }
}
